#include "buzzer.h"
#include <hosal_pwm.h>
#include <FreeRTOS.h>
#include <task.h>
#include <stdio.h>
#include "file_op.h"
#include "configs.h"

static note_t demo_music[] = {
    {M_DO, 100},
    {M_MI, 100},
    {M_SO, 100},
};

static hosal_pwm_dev_t buzzer;
static uint8_t is_enabled = 1;
static uint8_t volume = 0;

// 设置音量，范围0~30
void set_buzzer_volume(uint8_t vol)
{
    volume = vol;

    write_file(BUZZER_FILE, (const char *)&volume, 1);
    buzzer_out(1);
}

uint8_t get_buzzer_volume(void)
{
    return volume;
}


void buzzer_out(uint8_t value)
{
    if (value) {
        is_enabled = 1;
    } else {
        is_enabled = 0;
    }
}

static void buzzer_task(void *pvParameters)
{
    hosal_pwm_config_t para;

    para.duty_cycle = volume * 100;
    para.freq = L_DO;
    hosal_pwm_para_chg(&buzzer, para);
    hosal_pwm_start(&buzzer);
    vTaskDelay(100);
    hosal_pwm_stop(&buzzer);
    
    while (1) {
        if (!is_enabled) {
            vTaskDelay(200);
            continue;
        }

        hosal_pwm_start(&buzzer);
        for (int i = 0; i < sizeof(demo_music) / sizeof(note_t); i++) {
            para.duty_cycle = volume * 100;
            para.freq = demo_music[i].freq;
            hosal_pwm_para_chg(&buzzer, para);
            vTaskDelay(demo_music[i].duration);
        }
        hosal_pwm_stop(&buzzer);
        is_enabled = 0;
    }
}

void init_buzzer(void)
{
    int ret = read_file(BUZZER_FILE, (char *)&volume, 1);
    if (ret != 1) {
        volume = 30;
    }

    buzzer.config.pin = 5;
    buzzer.config.duty_cycle = volume * 100;      //占空比范围为：0~10000相当于0~100%
    buzzer.config.freq = 1;            //频率范围为 0~40MHZ
    buzzer.port = buzzer.config.pin % 5; // 端口 = 引脚 % 5
    hosal_pwm_init(&buzzer);

    xTaskCreate(buzzer_task, (char *)"buzzer task", 128, NULL, 36, NULL);
}

